<template>
  <view class="order-container">
    <!-- 订单筛选 -->
    <view class="order-filter">
      <text 
        class="filter-item" 
        :class="{active: statusFilter === 'all'}"
        @click="statusFilter = 'all'"
      >全部</text>
      <text 
        class="filter-item" 
        :class="{active: statusFilter === 'pending'}"
        @click="statusFilter = 'pending'"
      >待付款</text>
      <text 
        class="filter-item" 
        :class="{active: statusFilter === 'delivering'}"
        @click="statusFilter = 'delivering'"
      >配送中</text>
      <text 
        class="filter-item" 
        :class="{active: statusFilter === 'completed'}"
        @click="statusFilter = 'completed'"
      >已完成</text>
      <text 
        class="filter-item" 
        :class="{active: statusFilter === 'cancelled'}"
        @click="statusFilter = 'cancelle`d'"
      >已取消</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-mask" v-if="loading">
      <text>加载中...</text>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <!-- 空状态提示 -->
      <view class="empty-list" v-if="!loading && orders.length === 0">
        <text>暂无订单记录</text>
      </view>

      <!-- 订单项 -->
      <view 
        v-for="(order, index) in filteredOrders" 
        :key="index" 
        class="order-item"
      >
        <!-- 新增的创建时间显示区域 -->
        <view class="order-creation-time">
          <text>{{ order.items[0].time }}</text>
        </view>
        <view class="store-info">
          <image 
            class="store-icon" 
            :src="getShopImage(order.shopId)"
            v-if="getShopImage(order.shopId)"
          ></image>
          <text class="store-name">{{ getShopName(order.shopId) }}</text>
          <text class="order-status">{{ getStatusText(order.status) }}</text>
        </view>

        <view class="product-list">
          <view 
            v-for="(item, pIndex) in order.items" 
            :key="pIndex" 
            class="product-item"
          >
            <image 
              class="product-image" 
              :src="item.imgUrl"
              mode="aspectFill"
            ></image>
            <view class="product-info">
              <text class="product-name">{{ item.name }}</text>
              <view class="price-section">
                <text class="product-price">¥{{ item.price.toFixed(2) }}</text>
                <text class="product-quantity">x{{ item.count }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="order-footer">
          <text class="total-price">
            共{{ order.items.length }}件 合计：¥{{ calculateTotal(order.items).toFixed(2) }}
          </text>
          <view class="order-actions">
            <text 
              v-if="order.status === 'delivering'" 
              class="action-btn confirm-btn" 
              @click="confirmReceipt(order.id)"
            >确认收货</text>
            <text 
              v-if="order.status === 'delivering'" 
              class="action-btn cancel-btn" 
              @click="cancelOrder(order.id)"
            >取消订单</text>
            
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
<<<<<<< HEAD
import config from '../../config';

export default {
    data() {
        return {
            orders: [],
            shops: [],
            statusFilter: 'all',
            loading: true
        };
    },
    computed: {
        filteredOrders() {
            return this.orders.filter(order => 
                this.statusFilter === 'all' || order.status === this.statusFilter
            );
        }
    },
    methods: {
        confirmReceipt(orderId) {
            const order = this.orders.find(item => item.id === orderId);
            if (order) {
                order.status = 'completed';
                uni.showToast({
                    title: '已确认收货',
                    icon:'success'
                });
            }
        },
        cancelOrder(orderId) {
            const order = this.orders.find(item => item.id === orderId);
            if (order) {
                order.status = 'cancelled';
                uni.showToast({
                    title: '已取消订单',
                    icon:'success'
                });
            }
        },
        async fetchOrders() {
            try {
                const { data } = await uni.request({
                    url: config.URL + '/orders',
                    method: 'GET',
                    data: { userId: uni.getStorageSync('ID') }
                });
                // 添加默认状态处理
                this.orders = (data || []).map(order => ({
                   ...order,
                    status: order.status || 'delivering'
                }));
            } catch (error) {
                // 错误处理保持不变
            } finally {
                this.loading = false;
            }
        },
        async fetchShops() {
            try {
                const { data } = await uni.request({
                    url: config.URL + '/shop',
                    method: 'GET'
                });
                this.shops = data || [];
            } catch (error) {
                console.error('店铺加载失败:', error);
            }
        },
        calculateTotal(items) {
            return items.reduce((sum, item) => sum + (item.price * item.count), 0);
        },
        getShopName(shopId) {
            const shop = this.shops.find(s => s._id === shopId.toString());
            return shop? shop.name : '未知商家';
        },
        getShopImage(shopId) {
            const shop = this.shops.find(s => s._id === shopId.toString());
            return shop?.imgUrl || '';
        },
        getStatusText(status) {
            // 默认显示为配送中
            const statusMap = {
                pending: '待付款',
                delivering: '配送中',
                completed: '已完成',
                cancelled: '已取消'
            };
            return statusMap[status] || '配送中';
        }
    },
    onLoad() {
        this.fetchOrders();
        this.fetchShops();
    }
=======
import axios from 'axios';

export default {
  data() {
    return {
      orders: [],
      shops: [],
      statusFilter: 'all',
      loading: true
    };
  },
  computed: {
    filteredOrders() {
      return this.orders.filter(order => 
        this.statusFilter === 'all' || order.status === this.statusFilter
      );
    }
  },
  methods: {

 confirmReceipt(orderId) {
      const order = this.orders.find(item => item.id === orderId);
      if (order) {
        order.status = 'completed';
        uni.showToast({
          title: '已确认收货',
          icon: 'success'
        });
      }
    },

    // 取消订单方法（纯前端修改）
    cancelOrder(orderId) {
      const order = this.orders.find(item => item.id === orderId);
      if (order) {
        order.status = 'cancelled';
        uni.showToast({
          title: '已取消订单',
          icon: 'success'
        });
      }
    },




    // 获取订单数据
 async fetchOrders() {
    try {
      const res = await axios.get('http://localhost:3000/orders', {
        params: { userId: uni.getStorageSync('ID') }
      });
      // 添加默认状态处理
      this.orders = (res.data || []).map(order => ({
        ...order,
        status: order.status || 'delivering' // 如果订单没有状态字段，默认设为配送中
      }));
    } catch (error) {
      // 错误处理保持不变
    } finally {
      this.loading = false;
    }
  },

    // 获取店铺数据
    async fetchShops() {
      try {
        const res = await axios.get('http://localhost:3000/shop');
        this.shops = res.data || [];
      } catch (error) {
        console.error('店铺加载失败:', error);
      }
    },

    // 计算订单总价
    calculateTotal(items) {
      return items.reduce((sum, item) => sum + (item.price * item.count), 0);
    },

    // 获取店铺名称
    getShopName(shopId) {
      const shop = this.shops.find(s => s._id === shopId.toString());
      return shop ? shop.name : '未知商家';
    },

    // 获取店铺图片
    getShopImage(shopId) {
      const shop = this.shops.find(s => s._id === shopId.toString());
      return shop?.imgUrl || '';
    },

    // 状态文本映射
    getStatusText(status) {
      // 默认显示为配送中
      const statusMap = {
        pending: '待付款',
        delivering: '配送中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return statusMap[status] || '配送中'; // 将未知状态默认显示为配送中
    }


  

  },
  onLoad() {
    this.fetchOrders();
    this.fetchShops();
  }
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
};
</script>

<style scoped>
.order-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 筛选栏 */
.order-filter {
  display: flex;
  justify-content: space-around;
  background: #fff;
  padding: 20rpx 0;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.filter-item {
  font-size: 14px;
  color: #666;
  padding: 8rpx 16rpx;
}

.filter-item.active {
  color: #ff5500;
  font-weight: bold;
  border-bottom: 2px solid #ff5500;
}

/* 订单项 */
.order-item {
  background: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
}

/* 新增的创建时间样式 */
.order-creation-time {
  margin-bottom: 10rpx;
  color: #999;
  font-size: 14px;
}

.store-info {
  display: flex;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #eee;
  margin-bottom: 20rpx;
}

.store-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  margin-right: 10rpx;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
  flex: 1;
}

.order-status {
  color: #ff5500;
  font-size: 14px;
}

/* 商品项 */
.product-item {
  display: flex;
  margin-bottom: 20rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

.price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  color: #ff5500;
  font-size: 16px;
  font-weight: bold;
}

.product-quantity {
  color: #666;
  font-size: 14px;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1px solid #eee;
  margin-top: 20rpx;
}

.total-price {
  color: #ff5500;
  font-size: 16px;
  font-weight: bold;
}

/* 操作按钮 */
.order-actions {
  display: flex;
  gap: 10rpx;
}

.action-btn {
  padding: 8rpx 20rpx;
  border-radius: 30rpx;
  font-size: 12px;
}

.confirm-btn {
  border: 1px solid #ff5500;
  color: #ff5500;
}

.cancel-btn {
  border: 1px solid #999;
  color: #666;
}

.review-btn {
  border: 1px solid #09bb07;
  color: #09bb07;
}

/* 加载状态 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255,255,255,0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

/* 空状态 */
.empty-list {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 14px;
}
</style>